
import React, { useState, useEffect } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import remarkBreaks from "remark-breaks"; 
import rehypeHighlight from "rehype-highlight";
import rehypeSanitize from 'rehype-sanitize';
// import "highlight.js/styles/github.css"; // 代码高亮主题
import "highlight.js/styles/github-dark.css"; // 更换为暗色主题
// import { FiCopy } from 'react-icons/fi'; // 添加复制图标

import "./ContentRenderer.css";
// import { CopyToClipboard } from 'react-copy-to-clipboard';
// import LazyLoad from 'react-lazyload'; // 图片懒加载 

// 判断字符是否为文本字符，返回true或false
const isTextChar = (char) => {
  const code = char.charCodeAt(0);
  return (
    (code >= 48 && code <= 57) || // 数字 0-9
    (code >= 65 && code <= 90) || // 大写字母 A-Z
    (code >= 97 && code <= 122) || // 小写字母 a-z
    (code >= 0x4e00 && code <= 0x9fff) // 中文字符
  );
};

const copyToClipboard = (text) => {
  const textarea = document.createElement('textarea');
  textarea.value = text;
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand('copy');
  document.body.removeChild(textarea);
};

const CodeBlock = ({ node, inline, className, children, ...props }) => {
  const match = /language-(\w+)/.exec(className || "");
  const lang = match ? match[1] : "";
  // const childArray = React.Children.toArray(children);

  // 提取代码文本
  // const code = children[0]
  const [copied, setCopied] = useState(false);

  const handleCopy = () => {
    copyToClipboard(children);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return !inline ? (
    <div className="code-block-container">
      <pre className={`custom-code-block ${className || ""}`} {...props}>
        <code className={`language-${lang}`}>{children}</code>
      </pre>
      <button className="copy-button" onClick={handleCopy}>
        {copied ? '已复制' : '复制'}
      </button>
    </div>
  ) : (
    <code className={`inline-code ${className || ""}`} {...props}>
      {children}
    </code>
  );
};

/**
 * ContentRenderer组件用于渲染Markdown内容
 * 它使用了ReactMarkdown组件来解析和显示Markdown文本，并通过remarkGfm和rehypeHighlight来扩展Markdown的语法支持和代码高亮功能
 * 
 */
const ContentRenderer = ({ content, animate = true }) => {
  const [currentChar, setCurrentChar] = useState(0);

  useEffect(() => {
    let intervalId;
    if (content && animate) {
      // const suffix = "|"; // 定义后缀
      const interval = setInterval(() => {
        setCurrentChar((prevChar) => {

          if (prevChar < content.length) {

            let nextChar = prevChar + 1;

            // 跳过非文本字符
            while (nextChar < content.length && !isTextChar(content[nextChar])) {
              nextChar++;
            }

            // 确保 nextChar 不会超过 content.length
            nextChar = Math.min(nextChar, content.length);

            // 如果 nextChar 达到 content.length，清除定时器并设置 loading 为 false
            if (nextChar === content.length) {
              clearInterval(intervalId);
            }

            return nextChar;
          } 
          else {
            clearInterval(interval);
            return prevChar;
          }
        });
      }, 20); // 每20毫秒增加一个字符

      return () => clearInterval(interval);
    }else if (!animate) {
          setCurrentChar(content.length);
        }
  }, [content, animate]);

  // 使用 currentChar 截取 content 的一部分
  const displayedContent = content ? content.slice(0, currentChar) : '';


  // const handleCodeClick = (code) => {
  //   navigator.clipboard.writeText(code);
  //   alert("复制成功");
  // };

  return (
    <div className="content-renderer">
      {/* <Toaster /> */}
      <ReactMarkdown
        children={displayedContent}
        remarkPlugins={[remarkGfm,remarkBreaks]} // 支持表格、脚注等GitHub Markdown语法
        rehypePlugins={[rehypeHighlight, rehypeSanitize]} // 代码块高亮和内容清洗
        components={{
          // 自定义Markdown组件的样式和行为
          table: ({ children }) => (
            <table className="markdown-table">{children}</table>
          ),
          code: CodeBlock,
          // 新增 blockquote 样式覆盖
          blockquote: ({ children }) => (
            <blockquote className="custom-blockquote">{children}</blockquote>
          ),
          br: () => <br />, 
        }}

      />
    </div>
  );
};

export default ContentRenderer;